package com.yundingai.service.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *
 * @Date 2025/7/18 17:27
 * @Author yangming
 * @Description TODO
 **/
@Service
public class RedisAiCacheServiceImpl {
    @Autowired
     StringRedisTemplate redisTemplate;

    /**
     * @Author yangming
     * @Date 2025/7/18 21:31
     * @Description 定义实体类数据暂存聊天记录
     **/
    public static class ChatMessage {
        private String role;
        private String content;
        // getter/setter 必须提供
        public String getRole() { return role; }
        public void setRole(String role) { this.role = role; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }

    /**
     * @Author yangming
     * @Date 2025/7/18 23:52
     * @Description 保存完整响应到 Redis方法
     *
     **/
    public void saveFullResponseToRedis(String message, String fullResponse,String userid) throws JsonProcessingException {
        String redisKey = "chat:"+userid;
        ObjectMapper mapper = new ObjectMapper();

        // 解析用户消息
        List<ChatMessage> userMessages = mapper.readValue(message, mapper.getTypeFactory().constructCollectionType(List.class, ChatMessage.class));
        // 逐条保存用户消息
        for (ChatMessage userMsg : userMessages) {
            String userJson = mapper.writeValueAsString(userMsg);
            redisTemplate.opsForList().rightPush(redisKey, userJson);
        }

        // 添加 AI 回复（单独保存为一个元素）
        ChatMessage aiMsg = new ChatMessage();
        aiMsg.setRole("assistant");
        aiMsg.setContent(fullResponse);
        String aiJson = mapper.writeValueAsString(aiMsg);
        redisTemplate.opsForList().rightPush(redisKey, aiJson);

        // 设置过期时间
//        redisTemplate.expire(redisKey, 12, TimeUnit.HOURS);

    }

    /**
     * @Author yangming
     * @Date 2025/7/18 23:56
     * @Description 获取redis中缓存的聊天记录
     **/
    public List<ChatMessage> getChatHistory(String sessionId) {
        List<String> jsonList = redisTemplate.opsForList().range(sessionId, 0, -1);
        List<ChatMessage> history = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();

        for (String json : jsonList) {
            try {
                // 现在所有元素都是单个 ChatMessage
                ChatMessage message = mapper.readValue(json, ChatMessage.class);
                history.add(message);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return history;
    }

}
